package com.ruoyi.web.controller.system;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.ruoyi.common.bean.menu.MenuInfo;
import com.ruoyi.common.utils.excel.ExcelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.BaseResponse;
import com.ruoyi.system.domain.SysMenu;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysMenuService;

import jakarta.servlet.http.HttpServletResponse;

/**
 * 菜单信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController
{
    @Autowired
    private ISysMenuService menuService;

    /**
     * 获取菜单列表
     */
    @PreAuthorize("@ss.hasPermi('system:menu:list')")
    @GetMapping("/list")
    public BaseResponse list(SysMenu menu)
    {
        List<SysMenu> menus = menuService.selectMenuList(menu, getUserId());
        return success(menus);
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:menu:query')")
    @GetMapping(value = "/{menuId}")
    public BaseResponse getInfo(@PathVariable Long menuId)
    {
        return success(menuService.selectMenuById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public BaseResponse treeselect(SysMenu menu)
    {
        List<SysMenu> menus = menuService.selectMenuList(menu, getUserId());
        return success(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public BaseResponse<MenuInfo> roleMenuTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysMenu> menus = menuService.selectMenuList(getUserId());
        BaseResponse<MenuInfo> ajax = BaseResponse.success();
        MenuInfo menuInfo = new MenuInfo();
        menuInfo.setCheckedKeys(menuService.selectMenuListByRoleId(roleId));
        menuInfo.setMenus( menuService.buildMenuTreeSelect(menus));
        ajax.setData(menuInfo);
        return ajax;
    }

    /**
     * 新增菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:add')")
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public BaseResponse add(@Validated @RequestBody SysMenu menu)
    {
        if (!menuService.checkMenuNameUnique(menu))
        {
            return error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath()))
        {
            return error("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        menu.setCreateBy(getUsername());
        return toAjax(menuService.insertMenu(menu));
    }

    /**
     * 修改菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:edit')")
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public BaseResponse edit(@Validated @RequestBody SysMenu menu)
    {
        if (!menuService.checkMenuNameUnique(menu))
        {
            return error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath()))
        {
            return error("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        else if (menu.getMenuId().equals(menu.getParentId()))
        {
            return error("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(getUsername());
        return toAjax(menuService.updateMenu(menu));
    }

    /**
     * 删除菜单
     */
    @PreAuthorize("@ss.hasPermi('system:menu:remove')")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{menuId}")
    public BaseResponse remove(@PathVariable("menuId") Long menuId)
    {
        if (menuService.hasChildByMenuId(menuId))
        {
            return warn("存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId))
        {
            return warn("菜单已分配,不允许删除");
        }
        return toAjax(menuService.deleteMenuById(menuId));
    }

    /**
     * 数据测试专用接口
     * @param response
     * @throws Exception
     */
    @GetMapping(value = "/test/data")
    public void download( HttpServletResponse response) throws Exception {
        //download2(response);
        testReadOfProcessBuilder();

    }

    private void testReadOfProcessBuilder(){
        String codeType = "python";
        String pythonScriptPath = "D:/workSpace_py/HTMLSimilarity-master/HtmlCompare.py";
        String arg1 = "D:/workSpace_py/HTMLSimilarity-master/testHtml1.html";
        String arg2 = "D:/workSpace_py/HTMLSimilarity-master/testHtml2.html";
        int dimension = 5000;
        ProcessBuilder pb = new ProcessBuilder(codeType, pythonScriptPath, arg1, arg2, String.valueOf(dimension));
        try {
            Process process = pb.start();
            // StandardCharsets.UTF_8
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void testReadOfRuntimeExec(){
        String pythonScriptPath = "D:/workSpace_py/HTMLSimilarity-master/test.py";
        String arg1 = "Hello";
        String arg2 = "World";

        // 使用Runtime.exec()
        try {
            Process p = Runtime.getRuntime().exec(new String[]{"python", pythonScriptPath, arg1, arg2});
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String ret;
            while ((ret = in.readLine()) != null) {
                System.out.println(ret);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static final int PAGE_SIZE = 10000; // 每次查询的数据量

    private void download2(HttpServletResponse response) throws Exception{
        String fileName = "测试下载";
// 初始化ExcelWriter
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet writeSheet = EasyExcel.writerSheet(0, "Sheet1").build();

        // 查询总数据量
        long totalDataCount = getTotalDataCount();

        // 分页查询并写入Excel
        for (int pageNum = 1; (pageNum - 1) * PAGE_SIZE < totalDataCount; pageNum++) {
            List<Data> dataList = fetchData(pageNum, PAGE_SIZE);
            excelWriter.write(dataList,writeSheet);
        }
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName+".xlsx", "UTF-8"));

        // 关闭ExcelWriter
        excelWriter.finish();
        response.flushBuffer();
    }

    // 模拟从数据库中查询总数据量
    private static long getTotalDataCount() {
        // 实现获取总数据量的逻辑，可以是查询数据库，或者其他方式获取
        return 1000000; // 假设总数据量为100万条
    }

    // 模拟从数据库中分页查询数据
    private static List<Data> fetchData(int pageNum, int pageSize) {
        // 实现分页查询数据的逻辑，可以是查询数据库，或者其他方式获取
        // 示例中用pageNum和pageSize模拟了分页查询，你需要根据具体情况替换为实际的分页查询逻辑
        // 假设这里是从数据库中查询数据的逻辑
        int startIndex = (pageNum - 1) * pageSize + 1;
        int endIndex = pageNum * pageSize;
        // 这里返回的是一个假数据，实际应用中需要根据具体的业务逻辑从数据库中查询数据
        return DataGenerator.generateData(startIndex, endIndex);
    }

    // 数据实体类
    static class Data {
        private String name;
        private int age;

        // 省略getter和setter

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
    }

    // 模拟数据生成器
    static class DataGenerator {
        public static List<Data> generateData(int startIndex, int endIndex) {
            // 这里模拟生成[startIndex, endIndex]范围内的假数据
            // 实际应用中需要根据具体的业务逻辑从数据库中查询数据
            // 这里只是为了演示示例，生成了一些假数据
            List<Data> dataList = new ArrayList<>();
            for (int i = startIndex; i <= endIndex; i++) {
                Data data = new Data();
                data.setName("Name " + i);
                data.setAge(i % 100);
                dataList.add(data);
            }
            return dataList;
        }
    }

    private void download1(HttpServletResponse response) throws Exception{
        List<String> list01 = Arrays.asList("产品编码", "产品名称", "产品数量", "动态字段1", "动态字段2", "动态字段3");
        List<String> list02 = Arrays.asList("经销商编码", "经销商名称", "产品数量", "动态字段1", "动态字段2", "动态字段3");
        List<List<List<String>>> lists01 = ExcelClient.convertToHead(list01,list02);

        List<String> list03 = Arrays.asList("经销商编码", "经销商名称");
        List<List<List<String>>> lists03 = ExcelClient.convertToHead(list03);

        LinkedHashMap<String, List<List<List<String>>>> headMap = new LinkedHashMap<>();
        headMap.put("第一个sheet",lists01);
        headMap.put("第二个sheet",lists03);


        List<List> listData201 = ExcelClient.convertToData(list03,list03,list03);
        Map<String, List<List>> dataMap = new HashMap<>();
        dataMap.put("第二个sheet",listData201);


        ExcelClient.createDynamicExcel(headMap,dataMap,"动态excel",response);
    }




}

